// 1. 安装路由模块
// yarn add vue-router
// 2. 导入模块
import Vue from "vue";
import VueRouter from "vue-router";
import {getToken} from "@/utils/localData";
// 3. 注册路由组件 <router-view> 和 <router-link>
Vue.use(VueRouter);
// 4. 路由映射关系
const routes = [
	{
		path: "/",
		redirect: "/login",
	},
	{
		path: "/login",
		name: "login",
		component: () => import("@/views/login.vue"),
	},
	{
		path: "/register",
		name: "register",
		component: () => import("@/views/register.vue"),
	},
	{
		path: "/my",
		name: "My",
		component: () => import("@/views/My.vue"),
	},
	{
		path: "/mycompile", // 编辑
		name: "Mycompile",
		component: () => import("@/views/Mycompile.vue"),
	},
	{
		path: "/myattention", //关注
		name: "Myattention",
		component: () => import("@/views/Myattention.vue"),
	},
	{
		path: "/myfollow", // 跟帖
		name: "Myfollow",
		component: () => import("@/views/Myfollow.vue"),
	},
	{
		path: "/mycollect", // 收藏
		name: "Mycollect",
		component: () => import("@/views/Mycollect.vue"),
	},
	{
		path: "/myset", // 设置
		name: "Myset",
		component: () => import("@/views/Myset.vue"),
	},
	{
		path: "/index",
		name: "index",
		component: () => import("@/views/index.vue"),
	},
	{
		path: "/articleDetail",
		name: "articleDetail",
		component: () => import("@/views/articleDetail.vue"),
	},
	{
		path: "/reply",
		name: "reply",
		component: () => import("@/views/reply.vue"),
	},
	{
		path: "/column",
		name: "column",
		component: () => import("@/views/column.vue"),
	},
	{
		path: "/search",
		name: "search",
		component: () => import("@/views/search.vue"),
	},
];
// 5. new 一个路由实例
const router = new VueRouter({
	// routes? 有问号的提示，说明是 VueRouter 的提示
	routes,
});
// 路由守卫 - 就是一个路由跳转前自动执行的函数
//  to      目标路由对象地址(去哪里)
//  from    跳转前路由对象地址(从哪里来)
//  next    next是否放行(是一个函数)
router.beforeEach((to, from, next) => {
	// 可以在路由配置里添加元数据 meta: { check:true }
	//直接判断 to.meta.check
	// 部分页面访问的时候需要确认是否有token
	if (to.path.indexOf("/my") !== -1) {
		// 如果有成功获取到token
		if (getToken()) {
			next(); // 放行
		} else {
			next({name: "login"});
			// 没有 token 就跳转到登录页
		}
	} else {
		next(); // 普通页面，直接放行
	}
});
export default router; // 6.1 导出路由实例
